package mse.eai.jbpm.lotteryResultsProcess;

import java.util.ArrayList;

import org.jboss.logging.Logger;
import org.jbpm.graph.exe.ExecutionContext;
import org.jbpm.graph.node.DecisionHandler;

public class IsWinnersListEmpty implements DecisionHandler {

	private static final long serialVersionUID = -3442949152917984468L;
	private static final Logger log = Logger
			.getLogger(IsWinnersListEmpty.class);

	// must return YES or NO
	public String decide(ExecutionContext context) throws Exception {

		log.info("Executing ---------->");

		String transition = "YES";

		try {

			WinnersList lista = (WinnersList) context
					.getVariable("winnersList");
			
			log.info("Got from context: " + "winnersList  = " + context.getVariable("winnersList"));
			
			ArrayList<Winner> winnersList = lista.lista;

			if (winnersList.size() > 0) {

				Winner winner = winnersList.get(0);

				// PUT DATA IN CONTEXT
				context.setVariable("uid", winner.uid);
				context.setVariable("amount", winner.amount);

				log.info("Set in context: " + "uid  = " + winner.uid);
				log.info("Set in context: " + "amount  = " + winner.amount);
				
				// REMOVE FROM THE LIST
				winnersList.remove(0);
				context.setVariable("winnersList", lista);
				
				log.info("Set in context: " + "winnersList  = " + lista);

				transition = "NO";
			}
			
			log.info("transition chosen: " + transition);

		} catch (Exception ex) {
			log.error("Exception: ", ex);
			log.error("ProcessInstance will be suspended");
			context.getProcessInstance().suspend();
		}
		
		log.info("<--------------- Done");

		return transition;
	}
}